package logic

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"king/kingrpc/internal/svc"
	"king/kingrpc/kingrpc"
	"king/model/cache"
	"king/model/mysql"
	"king/pkg"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderAddLogic) OrderAdd(in *kingrpc.OrderAddRequest) (*kingrpc.OrderAddResponse, error) {
	// todo: add your logic here and delete this line
	tx := mysql.DB.Begin()
	if in.Quantity > 10 {
		return nil, fmt.Errorf("商品购买数量最多为10件")
	}

	var u mysql.User
	var p mysql.Product
	var err error
	err = tx.Debug().Where("id=?", in.UserId).First(&u).Error
	if err != nil {
		tx.Rollback()
		return nil, fmt.Errorf("用户不存在")
	}

	err = tx.Debug().Where("id=?", in.ProductId).First(&p).Error
	if err != nil {
		tx.Rollback()
		return nil, fmt.Errorf("商品不存在")
	}

	if in.Quantity > cache.GetStock(int(in.ProductId)) {
		tx.Rollback()
		return nil, fmt.Errorf("商品库存不足")
	}

	totalAmount := float64(in.Quantity) * p.Price

	order := mysql.Order{
		UserId:      int(in.UserId),
		OrderSn:     uuid.NewString(),
		TotalAmount: totalAmount,
		Status:      1,
		PayType:     2,
	}
	err = tx.Debug().Create(&order).Error
	if err != nil {
		tx.Rollback()
		return nil, fmt.Errorf("添加订单shib:%v", err)
	}

	orderItem := mysql.OrderItem{
		OrderId:      int(order.ID),
		ProductId:    int(in.ProductId),
		ProductTitle: p.Title,
		ProductPrice: p.Price,
		ProductStock: int(p.Stock),
		ProductImage: p.Image,
		TotalAmount:  totalAmount,
	}
	err = tx.Debug().Create(&orderItem).Error
	if err != nil {
		tx.Rollback()
		return nil, fmt.Errorf("创建订单项失败:%v", err)
	}

	err = tx.Debug().Model(mysql.Product{}).Where("id=?", in.ProductId).
		Update("stock", cache.GetStock(int(in.ProductId))-in.Quantity).Error
	if err != nil {
		tx.Rollback()
		return nil, fmt.Errorf("库存扣减失败:%v", err)
	}

	tx.Commit()

	amount := fmt.Sprintf("%.2f", totalAmount)
	url := pkg.Alipay(order.OrderSn, amount)
	return &kingrpc.OrderAddResponse{
		OrderId: int64(order.ID),
		Url:     url,
	}, nil
}
